import type { VbenFormSchema } from '#/adapter/form';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { AiPlatformsApiApi } from '#/api/ai/setting/platformsApi';
import type { DescriptionItemSchema } from '#/components/description';

import { h } from 'vue';

import { CommonStatusEnum, DICT_TYPE } from '@vben/constants';
import { getDictOptions } from '@vben/hooks';
import { handleTree } from '@vben/utils';

import { Typography } from 'ant-design-vue';

import { getBotCategoriesList } from '#/api/ai/bot/categories';
import { getBrandList } from '#/api/ai/llm/brand';
import { getDeptListCondition } from '#/api/system/dept';
import { DictBadge } from '#/components/dict-badge';
import DictTag from '#/components/dict-tag/dict-tag.vue';
import { getRangePickerDefaultProps } from '#/utils';

const { Paragraph } = Typography;
/** 新增/修改的表单 */
export function useFormSchema(): VbenFormSchema[] {
  return [
    {
      fieldName: 'id',
      component: 'Input',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'categoryId',
      label: '分类',
      component: 'ApiTreeSelect',
      componentProps: {
        allowClear: true,
        api: async () => {
          const data = await getBotCategoriesList({});
          return handleTree(data);
        },
        labelField: 'name',
        valueField: 'id',
        childrenField: 'children',
        placeholder: '请选择分类',
        treeDefaultExpandAll: true,
      },
      rules: 'selectRequired',
    },
    {
      fieldName: 'apiCode',
      label: 'API编码',
      component: 'Input',
      componentProps: {
        placeholder: '可为空，为空时系统会自动生成',
      },
    },
    {
      fieldName: 'apiName',
      label: 'API名称',
      rules: 'required',
      component: 'Input',
      componentProps: {
        placeholder: '请输入API名称',
      },
    },
    {
      fieldName: 'description',
      label: 'API描述',
      component: 'Textarea',
      componentProps: {
        rows: 4,
        placeholder: '请输入API描述',
      },
    },
    {
      fieldName: 'brand',
      label: '品牌/平台',
      rules: 'selectRequired',
      component: 'ApiSelect',
      componentProps(values) {
        return {
          api: () => getBrandList(),
          labelField: 'title',
          valueField: 'key',
          placeholder: '请输入供应商/平台',
          onChange: (value: string, option: any) => {
            if (value) {
              values.brandName = value ? option.title || '' : '';
            } else {
              values.brandName = '';
            }
          },
        };
      },
    },
    {
      fieldName: 'brandName',
      label: '平台名称',
      component: 'Input',
      componentProps: {
        placeholder: '请输入平台名称',
      },
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'baseUrl',
      label: '基础url',
      component: 'Input',
      componentProps: {
        placeholder: '请输入平台基础url地址',
      },
    },
    {
      fieldName: 'apiPath',
      label: 'API相对路径',
      component: 'Input',
      componentProps: {
        placeholder: '请输入API 相对路径（如/v1/workflows/run)',
      },
    },
    {
      fieldName: 'requestMethod',
      label: '请求方法',
      component: 'Select',
      componentProps: {
        options: [
          {
            label: 'get',
            value: 'get',
          },
          {
            label: 'post',
            value: 'post',
          },
        ],
        placeholder: '请输入请求方法（GET、POST 等）',
      },
    },
    {
      fieldName: 'contentType',
      label: '请求Content-Type',
      component: 'Select',
      componentProps: {
        options: [
          {
            label: 'application/json',
            value: 'application/json',
          },
          {
            label: 'multipart/form-data',
            value: 'multipart/form-data',
          },
          {
            label: 'text/plain',
            value: 'text/plain',
          },
          {
            label: 'application/x-www-form-urlencoded',
            value: 'application/x-www-form-urlencoded',
          },
        ],
        placeholder: '请选择请求 Content-Type',
      },
    },
    {
      fieldName: 'authType',
      label: '认证方式',
      component: 'Select',
      componentProps: {
        options: [
          {
            label: 'BEARER_TOKEN',
            value: 'BEARER_TOKEN',
          },
          {
            label: 'API_KEY',
            value: 'API_KEY',
          },
        ],
        placeholder: '请选择认证方式（如BEARER_TOKEN、API_KEY）',
      },
    },
    {
      fieldName: 'authConfigMap.apiKey',
      label: 'API Key',
      component: 'Input',
      componentProps: {
        placeholder: '请输入API Key',
      },
      dependencies: {
        triggerFields: ['authType'],
        show: (values) => values.authType === 'API_KEY',
      },
    },
    {
      fieldName: 'authConfigMap.clientId',
      label: '客户端id',
      component: 'Input',
      componentProps: {
        placeholder: '请输入客户端id',
      },
      dependencies: {
        triggerFields: ['authType'],
        show: (values) => values.authType === 'BEARER_TOKEN',
      },
    },
    {
      fieldName: 'authConfigMap.clientSecret',
      label: '客户端密钥',
      component: 'Input',
      componentProps: {
        placeholder: '请输入客户端密钥',
      },
      dependencies: {
        triggerFields: ['authType'],
        show: (values) => values.authType === 'BEARER_TOKEN',
      },
    },
    {
      fieldName: 'authConfigMap.appCode',
      label: '工作流code',
      component: 'Input',
      componentProps: {
        placeholder: '创建工作流后平台分配的唯一 code',
      },
      dependencies: {
        triggerFields: ['brand'],
        show: (values) => values.brand === 'dify',
      },
    },
    {
      fieldName: 'authConfigMap.botId',
      label: '智能体Id',
      component: 'Input',
      componentProps: {
        placeholder: '请输入扣子平台上智能体的唯一标识bot_id',
      },
      dependencies: {
        triggerFields: ['brand'],
        show: (values) => values.brand === 'coze',
      },
    },
    {
      fieldName: 'authConfigMap.workflowId',
      label: '工作流id',
      component: 'Input',
      componentProps: {
        placeholder: '请输入扣子平台上工作流发布后的ID(workflow_id)',
      },
      dependencies: {
        triggerFields: ['brand'],
        show: (values) => values.brand === 'coze',
      },
    },
    {
      fieldName: 'timeout',
      label: '超时时间（秒）',
      component: 'InputNumber',
      componentProps: {
        min: 0,
        placeholder: '请输入超时时间（秒）',
      },
    },
    {
      fieldName: 'retryCount',
      label: '重试次数',
      component: 'InputNumber',
      componentProps: {
        min: 0,
        max: 10,
        placeholder: '请输入重试次数',
      },
    },
    {
      fieldName: 'status',
      label: '状态',
      component: 'RadioGroup',
      componentProps: {
        options: getDictOptions(DICT_TYPE.COMMON_STATUS, 'number'),
        buttonStyle: 'solid',
        optionType: 'button',
      },
      defaultValue: CommonStatusEnum.ENABLE,
    },

    {
      fieldName: 'areaCode',
      label: '行政区划',
      component: 'ApiTreeSelect',
      componentProps: {
        api: async () => {
          const data = await getDeptListCondition({ type: 'area' });
          return handleTree(data);
        },
        labelField: 'name',
        valueField: 'id',
        childrenField: 'children',
        placeholder: '请选择行政区划',
        treeDefaultExpandAll: true,
        allowClear: true,
      },
    },
    {
      fieldName: 'unitId',
      label: '单位',
      component: 'ApiTreeSelect',
      dependencies: {
        triggerFields: ['areaCode'],
        componentProps: (values) => {
          return {
            // 关键：用 areaCode 作为 key，强制重新渲染
            key: values.areaCode || 'all',
            api: async () => {
              const data = await getDeptListCondition({
                type: 'unit',
                ...(values.areaCode ? { areaCode: values.areaCode } : {}),
              });
              return handleTree(data);
            },
            labelField: 'name',
            valueField: 'id',
            childrenField: 'children',
            placeholder: '请选择单位',
            treeDefaultExpandAll: false,
            allowClear: true,
          };
        },
        trigger(values, formApi) {
          // 清空值，避免残留
          formApi.setFieldValue('unitId', undefined);
        },
      },
    },
    {
      fieldName: 'deptId',
      label: '归属部门',
      component: 'ApiTreeSelect',
      dependencies: {
        triggerFields: ['unitId'],
        componentProps: (values) => {
          return {
            // 关键：用 unitId 作为 key，强制重新渲染
            key: values.unitId || 'all',
            api: async () => {
              const data = await getDeptListCondition({
                type: 'dept',
                ...(values.unitId ? { unitId: values.unitId } : {}),
              });
              return handleTree(data);
            },
            labelField: 'name',
            valueField: 'id',
            childrenField: 'children',
            placeholder: '请选择归属部门',
            treeDefaultExpandAll: false,
            allowClear: true,
          };
        },
        trigger(values, formApi) {
          // 清空值，避免残留
          formApi.setFieldValue('deptId', undefined);
        },
      },
    },
    {
      fieldName: 'sort',
      label: '排序值',
      component: 'InputNumber',
      componentProps: {
        min: 0,
        placeholder: '请输入排序值',
      },
    },
    {
      fieldName: 'systemFlag',
      label: '是否系统内置',
      component: 'RadioGroup',
      defaultValue: false,
      componentProps: {
        options: [
          {
            label: '是',
            value: true,
          },
          {
            label: '否',
            value: false,
          },
        ],
        buttonStyle: 'solid',
        optionType: 'button',
      },
    },
    {
      fieldName: 'publicStatus',
      label: '是否公开',
      component: 'RadioGroup',
      defaultValue: false,
      componentProps: {
        options: [
          {
            label: '是',
            value: true,
          },
          {
            label: '否',
            value: false,
          },
        ],
        buttonStyle: 'solid',
        optionType: 'button',
      },
    },
  ];
}

/** 详情页字段 */
export function useDetailSchema(): DescriptionItemSchema[] {
  return [
    {
      label: 'API编码',
      field: 'apiCode',
    },
    {
      label: 'API名称',
      field: 'apiName',
    },
    {
      label: '所属分类',
      field: 'categoryName',
    },
    {
      label: 'API描述',
      field: 'description',
      render: (val) =>
        h('div', {
          innerHTML: val,
          class: 'whitespace-pre-wrap text-sm leading-relaxed',
        }),
    },
    {
      label: '平台名称',
      field: 'brandName',
    },
    {
      label: '基础url地址',
      field: 'baseUrl',
    },
    {
      label: 'API相对路径',
      field: 'apiPath',
    },
    {
      label: '请求方法',
      field: 'requestMethod',
    },
    {
      label: '请求 Content-Type',
      field: 'contentType',
    },
    {
      label: '认证方式',
      field: 'authType',
    },
    {
      label: '客户端id',
      field: 'authConfigMap.clientId',
      show: (values) => values?.authType === 'BEARER_TOKEN',
    },
    {
      label: '客户端密钥',
      field: 'authConfigMap.clientSecret',
      show: (values) => values?.authType === 'BEARER_TOKEN',
    },
    {
      label: '工作流code',
      field: 'authConfigMap.appCode',
      show: (values) => values?.brand === 'dify',
    },
    {
      field: 'authConfigMap.botId',
      label: '智能体Id',
      show: (values) => values?.brand === 'coze',
    },
    {
      field: 'authConfigMap.workflowId',
      label: '工作流Id',
      show: (values) => values?.brand === 'coze',
    },
    {
      label: '超时时间（秒）',
      field: 'timeout',
    },
    {
      label: '重试次数',
      field: 'retryCount',
    },
    {
      label: '状态',
      field: 'status',
      render: (val) =>
        h(DictTag, {
          type: DICT_TYPE.COMMON_STATUS,
          value: val,
        }),
    },
    {
      label: '是否系统内置',
      field: 'systemFlag',
      render: (val) =>
        h(DictBadge, {
          value: val,
        }),
    },
    {
      label: '是否公开',
      field: 'publicStatus',
      render: (val) =>
        h(DictBadge, {
          value: val,
        }),
    },
    {
      label: '行政区划',
      field: 'areaName',
    },
    {
      label: '所属单位',
      field: 'unitName',
    },
    {
      label: '所属部门',
      field: 'deptName',
    },
    {
      label: '排序值',
      field: 'sort',
    },
  ];
}

/** 列表的搜索表单 */
export function useGridFormSchema(): VbenFormSchema[] {
  return [
    {
      fieldName: 'apiCode',
      label: 'API编码',
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '请输入API编码',
      },
    },
    {
      fieldName: 'apiName',
      label: 'API名称',
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '请输入API名称',
      },
    },
    {
      fieldName: 'description',
      label: 'API描述',
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '请输入API描述',
      },
    },
    {
      fieldName: 'brand',
      label: '品牌/平台',
      component: 'ApiSelect',
      componentProps: {
        api: () => getBrandList(),
        labelField: 'title',
        valueField: 'key',
        placeholder: '请输入供应商/平台',
      },
    },
    {
      fieldName: 'baseUrl',
      label: '平台基础url地址',
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '请输入平台基础url地址',
      },
    },
    {
      fieldName: 'apiPath',
      label: 'API相对路径',
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '请输入API相对路径',
      },
    },
    {
      fieldName: 'requestMethod',
      label: '请求方法',
      component: 'Select',
      componentProps: {
        allowClear: true,
        options: [
          {
            label: 'get',
            value: 'get',
          },
          {
            label: 'post',
            value: 'post',
          },
        ],
        placeholder: '请选择请求方法',
      },
    },
    {
      fieldName: 'contentType',
      label: '请求Content-Type',
      component: 'Select',
      componentProps: {
        allowClear: true,
        options: [
          {
            label: 'application/json',
            value: 'application/json',
          },
          {
            label: 'multipart/form-data',
            value: 'multipart/form-data',
          },
          {
            label: 'text/plain',
            value: 'text/plain',
          },
          {
            label: 'application/x-www-form-urlencoded',
            value: 'application/x-www-form-urlencoded',
          },
        ],
        placeholder: '请选择请求 Content-Type',
      },
    },
    {
      fieldName: 'authType',
      label: '认证方式',
      component: 'Select',
      componentProps: {
        allowClear: true,
        options: [
          {
            label: 'BEARER_TOKEN',
            value: 'BEARER_TOKEN',
          },
          {
            label: 'API_KEY',
            value: 'API_KEY',
          },
        ],
        placeholder: '请选择认证方式',
      },
    },
    {
      fieldName: 'status',
      label: '状态',
      component: 'Select',
      componentProps: {
        allowClear: true,
        options: getDictOptions(DICT_TYPE.COMMON_STATUS, 'number'),
        placeholder: '请选择状态',
      },
    },
    {
      fieldName: 'areaCode',
      label: '行政区划',
      component: 'ApiTreeSelect',
      componentProps: {
        api: async () => {
          const data = await getDeptListCondition({ type: 'area' });
          return handleTree(data);
        },
        labelField: 'name',
        valueField: 'id',
        childrenField: 'children',
        placeholder: '请选择行政区划',
        treeDefaultExpandAll: true,
        allowClear: true,
      },
    },
    {
      fieldName: 'unitId',
      label: '单位',
      component: 'ApiTreeSelect',
      dependencies: {
        triggerFields: ['areaCode'],
        componentProps: (values) => {
          return {
            // 关键：用 areaCode 作为 key，强制重新渲染
            key: values.areaCode || 'all',
            api: async () => {
              const data = await getDeptListCondition({
                type: 'unit',
                ...(values.areaCode ? { areaCode: values.areaCode } : {}),
              });
              return handleTree(data);
            },
            labelField: 'name',
            valueField: 'id',
            childrenField: 'children',
            placeholder: '请选择单位',
            treeDefaultExpandAll: false,
            allowClear: true,
          };
        },
        trigger(values, formApi) {
          // 清空值，避免残留
          formApi.setFieldValue('unitId', undefined);
        },
      },
    },
    {
      fieldName: 'deptId',
      label: '归属部门',
      component: 'ApiTreeSelect',
      dependencies: {
        triggerFields: ['unitId'],
        componentProps: (values) => {
          return {
            // 关键：用 unitId 作为 key，强制重新渲染
            key: values.unitId || 'all',
            api: async () => {
              const data = await getDeptListCondition({
                type: 'dept',
                ...(values.unitId ? { unitId: values.unitId } : {}),
              });
              return handleTree(data);
            },
            labelField: 'name',
            valueField: 'id',
            childrenField: 'children',
            placeholder: '请选择归属部门',
            treeDefaultExpandAll: false,
            allowClear: true,
          };
        },
        trigger(values, formApi) {
          // 清空值，避免残留
          formApi.setFieldValue('deptId', undefined);
        },
      },
    },
    {
      fieldName: 'categoryId',
      label: '分类ID',
      component: 'InputNumber',
      componentProps: {
        min: 0,
        placeholder: '请输入分类ID',
      },
    },
    {
      fieldName: 'systemFlag',
      label: '是否系统内置',
      component: 'Select',
      componentProps: {
        allowClear: true,
        options: [
          {
            label: '是',
            value: true,
          },
          {
            label: '否',
            value: false,
          },
        ],
        placeholder: '请选择是否系统内置',
      },
    },
    {
      fieldName: 'publicStatus',
      label: '是否公开',
      component: 'Select',
      componentProps: {
        allowClear: true,
        options: [
          {
            label: '公开',
            value: true,
          },
          {
            label: '私有',
            value: false,
          },
        ],
        placeholder: '请选择是否公开',
      },
    },
    {
      fieldName: 'createTime',
      label: '创建时间',
      component: 'RangePicker',
      componentProps: {
        ...getRangePickerDefaultProps(),
        allowClear: true,
      },
    },
  ];
}

/** 列表的字段 */
export function useGridColumns(): VxeTableGridOptions<AiPlatformsApiApi.PlatformsApi>['columns'] {
  return [
    { type: 'checkbox', width: 40 },
    {
      field: 'id',
      title: '平台API主键',
      minWidth: 120,
      visible: false,
    },
    {
      field: 'apiCode',
      title: 'API编码',
      minWidth: 120,
    },
    {
      field: 'apiName',
      title: 'API名称',
      minWidth: 200,
    },
    {
      field: 'description',
      title: 'API描述',
      minWidth: 260,
    },
    {
      field: 'brand',
      title: '品牌/平台',
      minWidth: 120,
      visible: false,
    },
    {
      field: 'brandName',
      title: '平台名称',
      minWidth: 160,
    },
    {
      field: 'baseUrl',
      title: '基础url地址',
      minWidth: 200,
    },
    {
      field: 'apiPath',
      title: 'API相对路径',
      minWidth: 200,
    },
    {
      field: 'requestMethod',
      title: '请求方法',
      minWidth: 120,
    },
    {
      field: 'contentType',
      title: '请求Content-Type',
      minWidth: 140,
    },
    {
      field: 'authType',
      title: '认证方式',
      minWidth: 120,
    },
    {
      field: 'timeout',
      title: '超时时间（秒）',
      minWidth: 120,
    },
    {
      field: 'retryCount',
      title: '重试次数',
      minWidth: 120,
    },
    {
      field: 'status',
      title: '状态 1有效 0无效',
      minWidth: 120,
    },
    {
      field: 'orgName',
      title: '所属组织',
      minWidth: 200,
    },
    {
      field: 'fullName',
      title: '所属用户',
      minWidth: 160,
    },
    {
      field: 'categoryName',
      title: '分类名称',
      minWidth: 120,
    },
    {
      field: 'sort',
      title: '排序值',
      minWidth: 120,
    },
    {
      field: 'systemFlag',
      title: '是否系统内置',
      minWidth: 120,
      cellRender: {
        name: 'CellDictBadge',
      },
    },
    {
      field: 'publicStatus',
      title: '是否公开',
      minWidth: 120,
      cellRender: {
        name: 'CellDictBadge',
      },
    },
    {
      field: 'createTime',
      title: '创建时间',
      minWidth: 160,
      formatter: 'formatDateTime',
    },
    {
      field: 'actions',
      title: '操作',
      width: 200,
      fixed: 'right',
      slots: { default: 'actions' },
    },
  ];
}
